package com.nttuan.view;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.EditText;

import com.nttuan.mycalender.R;

/**
 * Created by TuanNT on 11/4/2014.
 */
public class SlideEditText extends EditText {
    private final float STEP = 0.5f;
    private float posOld;
    private float currentValue = 0.0f;
    private boolean isMove = false;
    private boolean enable = true;
    private Context context;
    public SlideEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(!enable)
            return true;
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            posOld = event.getX();
            return true;
        }
        if (event.getAction() == MotionEvent.ACTION_MOVE) {
            isMove = true;
            float posNew = event.getX();
            if (posNew < posOld) {
                currentValue -= STEP;
                if(currentValue > 1)
                    this.setText((int)currentValue+"");
                else{
                    currentValue = 1;
                    this.setText(R.string.no_alarm);
                }
            }
            else {
                currentValue += STEP;
                this.setText((int)currentValue + "");
            }
            posOld = posNew;
            return true;
        }
        if (event.getAction() == MotionEvent.ACTION_UP) {
                if(!isMove)
                    this.setText((int)currentValue+++"");
            isMove = false;
            return true;
        }
        return false;
    }
    public void setValue(int value){
        currentValue = value;
        if(value == 0)
            this.setText(R.string.no_alarm);
        else
            this.setText(value+"");
    }
    public int getValue(){
        try{
          int val = Integer.parseInt(this.getText().toString());
            return val;
        }catch (Exception e){
            return 0;
        }
    }

    @Override
    protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
        if(text == null || text.equals("") || text.equals("0"))
            this.setText(R.string.no_description);
        super.onTextChanged(text, start, lengthBefore, lengthAfter);
    }

    public void setEnable(boolean enable) {
        this.enable = enable;
    }
}
